package com.shanzhu.tourism.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.shanzhu.tourism.domain.Product;
import com.shanzhu.tourism.domain.ProductOrder;
import com.shanzhu.tourism.domain.ProductOrderItem;
import com.shanzhu.tourism.domain.Result;
import com.shanzhu.tourism.mapper.ProductMapper;
import com.shanzhu.tourism.mapper.ProductOrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: cc
 * @Date: 2025/03/28/15:06
 **/
@Service
@Slf4j
public class ProductService {

    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ProductOrderMapper orderMapper;

    public Product getProductById(Long productId) {
        try {
            return productMapper.selectById(productId);
        } catch (Exception e) {
            log.error("获取商品详情失败", e);
            return null;
        }
    }


    public Result getProductList(Product product) {
        try {
            List<Product> products = productMapper.selectList(product);
            return Result.success(products);
        } catch (Exception e) {
            return Result.fail("获取商品列表失败", e);
        }
    }

    @Transactional
    public Result createOrder(ProductOrder order) {
        try {
            // 1. 生成订单号
            order.setOrderNo(generateOrderNo());

            // 2. 计算订单总金额
            BigDecimal totalAmount = BigDecimal.ZERO;
            for (ProductOrderItem item : order.getOrderItems()) {
                Product product = productMapper.selectById(item.getProductId());
                if (product == null) {
                    return Result.fail("商品不存在");
                }

                // 检查库存
                if (product.getStock() < item.getQuantity()) {
                    return Result.fail(product.getProductName() + "库存不足");
                }

                // 计算商品总价
                item.setPrice(product.getPrice());
                item.setTotalPrice(product.getPrice().multiply(new BigDecimal(item.getQuantity())));
                totalAmount = totalAmount.add(item.getTotalPrice());

                // 扣减库存
                productMapper.updateStock(product.getProductId(), -item.getQuantity());
            }

            // 3. 保存订单
            order.setTotalAmount(totalAmount);
            order.setPayAmount(totalAmount);
            order.setOrderStatus(0); // 待支付
            orderMapper.insert(order);

            // 4. 保存订单项
            orderMapper.insertOrderItems(order.getOrderItems());

            return Result.success("下单成功");
        } catch (Exception e) {
            return Result.fail("下单失败", e);
        }
    }

    private String generateOrderNo() {
        return DateUtil.format(new Date(), "yyyyMMddHHmmss") + RandomUtil.randomNumbers(6);
    }


    public List<ProductOrder> getOrderList(Long userId) {
        try {
            List<ProductOrder> orders = orderMapper.selectByUserId(userId);
            // 查询每个订单的明细
            for (ProductOrder order : orders) {
                List<ProductOrderItem> items = orderMapper.selectOrderItems(order.getOrderId());
                order.setOrderItems(items);
            }
            return orders;
        } catch (Exception e) {
            log.error("获取订单列表失败", e);
            return null;
        }
    }
}
